<?php

namespace Application\Controller;

use Application\Model\Dao\UserDao;
use Application\Service\EmailService;
use Application\Service\PasswordService;
use Zend\Form\Element\Email;
use Zend\View\Model\ViewModel;
use Zend\Mvc\Controller\AbstractActionController;
use Zend\Authentication\AuthenticationService;
use Zend\View\Model\JsonModel;
use Zend\Math\Rand;
use Zend\Session\Container;

class GuestUserController extends AbstractActionController {
	
	private $FORGETPASSWORD_FLOW_START_FLAG = "FORGETPASSWORD_FLOW_START_FLAG";
	
	private $FORGETPASSWORD_EMAIL_VERIFIED = "FORGETPASSWORD_EMAIL_VERIFIED";
	
	private $FORGETPASSWORD_SECRET_VERIFIED = "FORGETPASSWORD_SECRET_VERIFIED";
	

	public function loginAction() {

		$auth = new AuthenticationService ();

		if ($auth->getIdentity ()) {
			$this->redirect ()
				->toUrl ( "/" );
		} else {

			$req = $this->request;
            $userName = $req->getPost ( "email" );
            $password = $req->getPost ( "password" );
            if(!$req->isPost()){
                $layout = $this->layout ();
                $layout->setTemplate ( 'layout/login' );
                $view = new ViewModel ();
                $view->setTemplate ( '/application/user/login' );
                return $view;
            }


			$user = $auth->authenticate ( new Auth\AuthAdapter ( $userName, $password) );

			if ($user->isValid ()) {
				// get the article from the persistence layer, etc...
				// Get the "layout" view model and set an alternate template
                $this->redirect ()
                    ->toUrl ( "/" );
			} else {

				// get the article from the persistence layer, etc...
				// Get the "layout" view model and set an alternate template
                $layout = $this->layout ();
                $layout->setTemplate ( 'layout/login' );
				// Create and return a view model for the retrieved article
				$view = new ViewModel ( array (
						'result' => 'failure' 
				) );
				$view->setTemplate ( '/application/user/login' );
				return $view;
			}
		}
	}
	
	private function putDataIntoGuestUserSession($key, $value){
		$container = new Container('guest');
		$container->$key = $value;
	}
	
	private function getDataFromGuestUserSession($key){
		$container = new Container('guest');
		return $container->$key;
	}
	
	private function destroyGuestUserSession(){
		$container = new Container('guest');
		unset($container);
	}
	
	public function forgotPasswordAction() {
		$layout = $this->layout ();
		$this->putDataIntoGuestUserSession($this->FORGETPASSWORD_FLOW_START_FLAG, true);
		$layout->setTemplate ( 'layout/login' );
		// Create and return a view model for the retrieved article
        $view = null;
        if($this->request->getQuery('email') != null){
            $view = new ViewModel(array('email' => $this->request->getQuery('email')) );
        } else {
            $view = new ViewModel();
        }
		$view->setTemplate ( '/application/user/forgot-password' );
		return $view;
	}
	
	public function fpPostEmailAction() {
		$layout = $this->layout ();
		if($this->getDataFromGuestUserSession($this->FORGETPASSWORD_FLOW_START_FLAG) == null ){
			return null;
		}
		$req = $this->request;
		$email = $req->getPost("email");
		$userDao = $this->getServiceLocator()->get("user");
		$user = $userDao->getUserByEmail($email);
		if($user != null){
			$this->putDataIntoGuestUserSession($this->FORGETPASSWORD_EMAIL_VERIFIED, $email);
			$secret = Rand::getString(10);
			$userDao->saveUserSecret($email, $secret);
            $emailService = new EmailService();
            $emailService->sendSecreteEmail($email,$secret);
			// send email of secret.
		} else {
			$view = new ViewModel ( array (
					'result' => 'failure'
			) );
			$view->setTemplate ( '/application/user/forgot-password' );
			return $view;
		}
		$layout->setTemplate ('layout/login');
		$view = new ViewModel ( array (
				'email' => $email,
		) );
		// Create and return a view model for the retrieved article
		$view->setTemplate ( '/application/user/forgot-password-secret.phtml' );
		return $view;
	}
	
	
	public function enterPasswordSecretAction() {
		$email = null;
		if($this->getDataFromGuestUserSession($this->FORGETPASSWORD_EMAIL_VERIFIED) == null ){
			return null;
		} else {
			$email = $this->getDataFromGuestUserSession($this->FORGETPASSWORD_EMAIL_VERIFIED);
		}
		$req = $this->getRequest();
		$secret = $req->getPost ("secret");
		$userDao = $this->getServiceLocator()->get("user");
		$user = $userDao->getUserByUNS($email, $secret);
		$layout = $this->layout ();
		$layout->setTemplate ( 'layout/login' );
		if($user != null){
			$view = new ViewModel ();
			$this->putDataIntoGuestUserSession($this->FORGETPASSWORD_SECRET_VERIFIED, true);
		} else {
			$view = new ViewModel ( array (
					'result' => 'failure'
			));
			$view->setTemplate ( '/application/user/forgot-password-secret' );
			return $view;
		}
		// Create and return a view model for the retrieved article
		$view->setTemplate ( '/application/user/change-password' );
		return $view;
	}
	
	public function resetPasswordAction() {
		
		if($this->getDataFromGuestUserSession($this->FORGETPASSWORD_SECRET_VERIFIED) == null ){
			return null;
		}
        $email = $this->getDataFromGuestUserSession($this->FORGETPASSWORD_EMAIL_VERIFIED);
		$req = $this->getRequest();
		$password = $req->getPost ("password");
        $userDao = $this->getServiceLocator()->get("user");

        $ps = new PasswordService();

        $user = $userDao->resetPassword($email,$ps->create_hash($password));

		$layout = $this->layout ();
		$layout->setTemplate ( 'layout/login' );

		// Create and return a view model for the retrieved article
		$view = new ViewModel ( array (
				'result' => 'failure'
		));
		$view->setTemplate ( '/application/user/password-successful-change' );
		return $view;
	}

	public function signupGetAction() {
		$layout = $this->layout ();
		$layout->setTemplate ( 'layout/login' );
		// Create and return a view model for the retrieved article
		$view = new ViewModel ( array (
				'result' => 'failure' 
		) );
		$view->setTemplate ( '/application/user/signup' );
		return $view;
	}

	public function signupAction() {
		$req = $this->getRequest ();
		$email = $req->getPost ( "userName" );
		$name = $req->getPost ( "fullName" );
		$password = $req->getPost ( "password" );
		$userDao = $this->getServiceLocator ()
			->get ( 'user' );
        $ps = new PasswordService();

		$result = $userDao->updateInvitedUser ( $name, $email, $ps->create_hash($password) );
        if($result != null){
            $view = new ViewModel ($result);
            $view->setTemplate ( '/application/user/signup' );
            return $view;
        }
		$auth = new AuthenticationService ();
		$user = $auth->authenticate ( new Auth\AuthAdapter ( $email, ($password) ) );
        $emailService = new EmailService();
        $emailService->sendRegistrationEmail($email);

		$this->redirect ()
			->toUrl ( "/user/signupApartmentGet" );
	}

	public function isEmailRegistered() {
		$req = $this->getRequest ();
		$email = $req->getQuery ( "email" );
		$userDao = $this->getServiceLocator ()
			->get ( 'user' );
		$user = $userDao->getUserByEmail ( $email );
		return new JsonModel ( $user );
	}

	public function recentlyJoinedUserAction() {
        $userDao = $this->getServiceLocator ()
            ->get ( 'user' );
        $users = $userDao->getRecentlyAddedUser();
        return new JsonModel ( $users );
	}

    public function userSearchedFormAction() {
        $userDao = $this->getServiceLocator ()
            ->get ( 'user' );
        $users = $userDao->getRecentlyAddedUser();
        return new JsonModel ( $users );
    }

    public function userSearchAction() {
        $req = $this->getRequest();
        $flatNo = $req.getQuery('flatNo');
        $profession = $req.getQuery('profession');
        $email = $req.getQuery('email');
        $userDao = $this->getServiceLocator ()
            ->get ( 'user' );
        $users = $userDao->getRecentlyAddedUser();
        return new JsonModel ( $users );
    }

    public function userSearchByNameAction() {
        $userDao = $this->getServiceLocator ()
            ->get ( 'user' );
        $users = $userDao->getRecentlyAddedUser();
        return new JsonModel ( $users );
    }



    private function getUserFromSession(){
        $auth = new AuthenticationService();
        if ($auth->getIdentity()) {
            $userDao = new UserDao();
            return $userDao->getUserByIdWithGroup($auth->getIdentity()->id);
        }
    }


    public function aboutusAction(){
        $layout = $this->layout ();
        $layout->setTemplate ( 'layout/layout' );
        $view = new ViewModel ();
        $view->setTemplate ( '/application/guest/aboutus' );
        return $view;
    }




}
